// pages/detail/detail.js
import { classifyList } from "../../config/api";
import {
	shareOptions
} from "../../utils/access";
import request from "../../utils/request";
import tim from "../../utils/tim/tim";
import { getBarAndTitleHeight, getStorage, getTimUserId, setStorage } from "../../utils/utils"
const api = require("../../config/api");

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		latitude: "",
		longitude: "",
		isLoaing: false,
		tabActive: 10,
		sendTabActive: 1,
		current: 1,
		pages: 0,
		scrollTop: "",
		scrollTopFlag: true,
		firstTabList: [{
				text: "全部",
				id: 10,
			},
			{
				text: "同小区",
				id: 20,
			},
		],
		labelList: [{
				text: "免费拿"
			},
			{
				text: "几乎全新",
			},
			{
				text: "功能完美",
			},
		],
		secondTabList: [

			{
				text: "推荐",
				id: 1,
			},
			{
				text: "热门",
				id: 2,
			},
			{
				text: "最新发布",
				id: 3,
			},
			{
				text: "离我最近",
				id: 4,
			},
		],
		secondTabListTwo: [{
			text: "推荐",
			id: 1
		},
		{
			text: "热门",
			id: 2
		},
		{
			text: "最新发布",
			id: 3
		},
	],
	// 显示全部和同小区不同的标题栏 1:全部，2同小区
	isShowTabs:1,
		goodsList: [],
		menuList: [],
		classifyList: [],
		communityBind: false,
		communityId:"",
		// 信号栏高度
    ...getBarAndTitleHeight(),
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		wx.setNavigationBarColor({
			frontColor: "#000000",
			backgroundColor: "#f5f5f5",
		});
		if (options?.inviteData) {
			setStorage('inviteData', options?.inviteData)
			console.log('分享人数据：', options.inviteData)
		}
	},

// 展示草稿保存提示
async	showDraftModal(params){
			console.log('----草稿',params)
			wx.showModal({
				title: '提示',
				content: '是否保存草稿？',
				confirmText: '保存',
				cancelText: '不保存',
				async success(res) {
					 if (res.confirm) { //保存草稿
					 let res= await request.post(api.addTempGoods, params,{loading: true})
					 if(res.httpStatus=== 200){
						wx.showToast({
							title: '保存成功',
							icon: 'none'
						})
					 }
					} else if (res.cancel) {//不保存，删除草稿
						if(!params.id) return //没有草稿
						let res= await request.post(api.deleteTempGoods, {id: params.id},{loading: true})
						 if(res.httpStatus=== 200){
							wx.showToast({
								title: '删除成功',
								icon: 'none'
							})
						}
					}
				}
			})
	},

	goGoodsClassify() {
		wx.navigateTo({
			url: '/pages/goodsClassify/goodsClassify',
		})
	},
	goGoodsSearch() {
		wx.navigateTo({
			url: '/pages/goodsSearch/goodsSearch',
		})
	},
	goSubClassify(e){
		let {id,pid,name} = e.currentTarget.dataset;
		console.log("PPPPPP",e);
		wx.navigateTo({
      url: `/pages/goodsSubClassify/goodsSubClassify?goodsClassifyId=${pid}&goodsSubClassifyId=${id}&title=${name}`,
    })
	},
	async getInfo() {
		const userId = getStorage("userId");
		if (userId) {
			const res = await request.get(
				api.homeDetail, {
					userId
				}, {
					loading: false
				}
			);
			//重新赋值 缓存信息
			setStorage("communityBind", res?.data.communityBind || false);
			setStorage("communityName", res?.data.communityName || " ");
			setStorage("communityId", res?.data.communityId || " ");
			this.setData({
				communityBind: res?.data.communityBind,
				communityId: res?.data.communityId
			});
		}
	},

	//获取全部商品列表
	async getGoodsList() {
		const lat = getStorage("latitude");
		const lon = getStorage("longitude");
		const { province,  city, direct  } = getStorage('addressInfo') || {}
		let {
			sendTabActive,
			current
		} = this.data;
		const {
			data
		} = await request.get(api.allGoods, {
			page: current,
			size: 10,
			lat,
			lon,
			type: sendTabActive,
			provinceName: province || '',
      cityName: city|| '',
      districtName: direct || ''
		});
		console.log("PPPPPP",this.data);
		this.setData({
			isShowTabs:1,
			goodsList: (this.data.current === 1 ?
				data?.records || [] : [...this.data.goodsList, ...data?.records]).map(item => ({
					...item,
					goodsSignList: (item.goodsSignList || item.goodsSigns)?.map(sign => sign.replace('#', ''))
				})),
			total: data?.total,
			current: data?.current,
			pages: data?.pages,
		});
		wx.stopPullDownRefresh();
	},
	//获取商品列表
	async getClassifyList() {
		const res = await request.get(api.classifyList, {});
		let arrs = [];
		res.data.forEach(item => {
			if (item.list.length > 1) {
				item.list.map(items => {
					if (items.id !== 0) {
						items.pid = item.id;
						return arrs.push(items)
					}
				})
			}
		})
		this.setData({
			menuList: arrs,
			classifyList:res.data,
		});
	},
	//获取小区商品列表
	async getCommunityList() {
		const lat = getStorage("latitude");
		const lon = getStorage("longitude");
		let {
			sendTabActive,
			current
		} = this.data;
		const {
			data
		} = await request.get(
			api.communityGoods, {
				page: current,
				size: 10,
				lat,
				lon,
				type: sendTabActive,
			}, {
				loading: false,
			}
		);
		console.log("hhhhhhhh");
		this.setData({
			isShowTabs:2,
			goodsList: (this.data.current === 1 ?
				data.records || [] : [...this.data.goodsList, ...data.records]).map(item => ({
					...item,
					goodsSignList: (item.goodsSignList || item.goodsSigns)?.map(sign => sign.replace('#', ''))
				})),
			total: data.total,
			current: data.current,
			pages: data.pages,
		});
		wx.stopPullDownRefresh();
	},
	handleTab(e) {
		if (e.currentTarget.dataset.index == 10) {
			this.setData({
				tabActive: e.currentTarget.dataset.index,
				sendTabActive:1,
				goodsList: [],
				secondTabList: [{
						text: "推荐",
						id: 1
					},
					{
						text: "热门",
						id: 2
					},
					{
						text: "最新发布",
						id: 3
					},
					{
						text: "离我最近",
						id: 4
					},
				],
				secondTabListTwo: [{
					text: "推荐",
					id: 1
				},
				{
					text: "热门",
					id: 2
				},
				{
					text: "最新发布",
					id: 3
				},
			],
				current: 1,
			});
			this.getGoodsList();
		} else {
			if (!this.data.communityBind) {
				wx.showModal({
					content: "请先绑定小区!",
					confirmText: "去绑定",
					success: function (res) {
						if (res.confirm) {
							wx.navigateTo({
								url: `/pages/idleCommunityList/idleCommunityList`,
							});
						}
					},
				});
				return false;
			} else {
				this.setData({
					tabActive: e.currentTarget.dataset.index,
					sendTabActive:1,
					goodsList: [],
					secondTabList: [{
							text: "推荐",
							id: 1
						},
						{
							text: "热门",
							id: 2
						},
						{
							text: "最新发布",
							id: 3
						},
						{
							text: "离我最近",
							id: 4
						},
					],
					current: 1,
				});
				this.getCommunityList();
			}
		}
	},
	handleSendTab(e) {
		console.log("FFFFFFFFF",e.currentTarget.dataset.index);
		let {
			current,
			tabActive
		} = this.data;
		this.setData({
			sendTabActive: e.currentTarget.dataset.index,
			current: 1,
		});
		if (tabActive == 10) {
			this.getGoodsList();
		} else {
			this.getCommunityList();
		}
	},
	handleGoodsDetail(event) {
		wx.navigateTo({
			url: `/pages/idleGosDetail/idleGosDetail?goodsId=` + event.currentTarget.id,
		});
	},
	handleAddGoods() {
		if (!this.data.communityBind) {
			wx.showModal({
				content: "请先绑定小区!",
				confirmText: "去绑定",
				success: function (res) {
					if (res.confirm) {
						wx.navigateTo({
							url: `/pages/idleCommunityList/idleCommunityList`,
						});
					}
				},
			});
			return false;
		} else {
			wx.navigateTo({
				url: `/pages/idleRelease/idleRelease`,
			});
		}
	},
	// 点击tab标签
	tabClick(){},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
	
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.getInfo();
		this.setData({
			current: 1,
		});

		if (this.data.tabActive == 10) {
			this.getGoodsList();
		} else if (this.data.tabActive == 20) {
			this.getCommunityList();
		}
		this.getClassifyList();
		this.getMessage()
	},
	// 获取im会话消息
	async getMessage() {
		if (getStorage('userId')) {
      const userId = getTimUserId(getStorage('userId'))
      const res = await request.get(api.isImUser, { userId })
      if (res?.data) {
        await tim.login()
				const conversationList = await tim.getMessageList()
				this.setData({
					hasNotice: conversationList.some(item => item.unreadCount)
				})
      }
    }
	},
	//点击回到顶部
	handleGoToTop() {
		wx.pageScrollTo({
			scrollTop: 0, // 滚动到页面的目标位置，单位 px
			duration: 500 // 滚动动画的时长，单位 ms
		})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {
		if (this.data.tabActive == 10) {
			this.getGoodsList();
		} else {
			this.getCommunityList();
		}
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {
		let {
			current,
			pages
		} = this.data;
		// page是当前页码乘以默认值 ==》当前数据总量
		if (current < pages) {
			// current 当前页码值
			this.setData({
				current: this.data.current + 1,
			});
			// 调用接口，发送请求，获得后续的数据
			if (this.data.tabActive == 10) {
				this.getGoodsList(current);
			} else if (this.data.tabActive == 20) {
				this.getCommunityList(current);
			}
		} else {
			this.setData({
				isLoaing: true,
			});
		}
	},

	// 用户点击右上角分享
	onShareAppMessage(e) {
		return shareOptions('idle', e)
	},
	onPageScroll(e) {
		let _this = this;
		let Top = e.scrollTop;
		_this.setData({
			scrollTop: Top
		})

		if (Top > 300) {
			_this.setData({
				scrollTopFlag: false
			})
		} else {
			_this.setData({
				scrollTopFlag: true
			})
		}
	}
});